package com.news.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.news.R;
import com.news.di.component.AppComponent;
import com.news.di.component.DaggerFragmentComponent;
import com.news.di.component.FragmentComponent;
import com.news.di.module.FragmentModule;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created with Android Studio
 * User: ShiLiang
 * Date: 2017/3/2/0002
 * Project: TodayNews
 */

public abstract class BaseFragment extends Fragment {

    protected View mRootView;
    private Unbinder mUnBinder;
    protected Context mContext;
    protected Activity mActivity;
    private boolean hasProgress = false;
    protected ProgressBar mProgressBar;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
        mActivity = (Activity) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(getLayoutId(), container, false);
        View root  = mRootView;
        if (hasProgress){
            ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(mContext).inflate(R.layout.fragment_base, null);
            mProgressBar = ((ProgressBar) viewGroup.findViewById(R.id.base_progress));
            viewGroup.addView(mRootView);
            root = viewGroup;
        }
        initInject();
        return root;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mUnBinder = ButterKnife.bind(this, view);

        initViews();
        loadData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mUnBinder.unbind();
    }

    public void setHasProgress(boolean hasProgress) {
        this.hasProgress = hasProgress;
    }

    protected FragmentComponent getFragmentComponent() {
        return DaggerFragmentComponent.builder()
                .appComponent(getAppComponent())
                .fragmentModule(getFragmentModule())
                .build();
    }

    private AppComponent getAppComponent() {
        return ((BaseApp) mActivity.getApplication()).getAppComponent();
    }

    private FragmentModule getFragmentModule() {
        return new FragmentModule(this);
    }

    public abstract int getLayoutId();

    public abstract void initViews();

    public abstract void loadData();

    protected abstract void initInject();
}
